<script>
import { defineComponent, reactive, toRefs, ref } from "vue";
import { getFileList, fileDownloadByPath, deleteFileById } from "@/api/file.js";
import { Search, Download, Delete } from "@element-plus/icons-vue";
import streamSaver from "streamsaver";
import { useUserStore } from "@/store/modules/user.js";

export default defineComponent({
  setup() {
    const defaultTime1 = new Date(2001, 1, 1, 0, 0, 0);
    const defaultTime2 = new Date(2001, 1, 1, 23, 59, 59);

    const state = reactive({
      fileType: "",
      typeOptions: [
        {
          label: "定时",
          value: 1,
        },
        {
          label: "手动",
          value: 0,
        },
      ],
      startTime: "",
      endTime: "",
      tableData: [],
      selectFile: {},
    });

    const icons = reactive({
      Search,
      Download,
      Delete,
    });

    const fileTable = ref(null);

    const store = useUserStore();
    //查找符号条件的文件
    const searchFile = () => {
      // if (
      //   state.startTime !== "" &&
      //   state.endTime !== "" &&
      //   state.fileType !== ""
      // ) {
      getFileList({
        endTime: state.endTime,
        fileType: state.fileType,
        startTime: state.startTime,
        fileSuffix: 1,
      }).then(
        (res) => {
          if (res.code === 200) {
            state.tableData = res.data;
          } else {
            ElMessage({
              message: res.message,
              type: "warning",
            });
          }
        },
        (err) => {
          ElMessage({
            message: err.message,
            type: "warning",
          });
        }
      );
      // }
    };

    //文件下载
    const fileDownload = async () => {
      if (!state.selectFile.src) {
        return;
      }
      let fullPath = state.selectFile.src;

      await fetch(`api/file/download?fullPath=${fullPath}`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${store.token}`,
        },
      }).then((res) => {
        fileTable.value.clearSelection();
        let name = state.selectFile.fileName;
        state.selectFile = {};
        const fileStream = streamSaver.createWriteStream(name, {
          size: res.headers.get("content-length"),
        });
        const readableStream = res.body;

        if (window.WritableStream && readableStream.pipeTo) {
          return readableStream.pipeTo(fileStream).then(() => {});
        }

        window.writer = fileStream.getWriter();
        const reader = res.body.getReader();
        const pump = () =>
          reader
            .read()
            .then((res) =>
              res.done
                ? window.writer.close()
                : window.writer.write(res.value).then(pump)
            );
        pump();
      });
    };

    //取消文件下载
    const cancelDown = () => {};

    //删除文件
    const deleteFile = () => {
      if (state.selectFile.id.length <= 0) {
        return;
      }
      let id = state.selectFile.id;
      deleteFileById(id).then(
        (res) => {
          ElMessage({
            message: "删除成功",
            type: "success",
            offset: 400,
          });
          searchFile();
        },
        (err) => {
          ElMessage({
            message: "删除失败",
            type: "warning",
            offset: 400,
          });
        }
      );
    };

    //选择文件时
    const handleSelectionChange = (any, val) => {
      console.log(val)
      fileTable.value.clearSelection();
      fileTable.value.toggleRowSelection(val);
      state.selectFile = val;
    };

    return {
      ...toRefs(state),
      ...toRefs(icons),
      searchFile,
      fileDownload,
      cancelDown,
      deleteFile,
      handleSelectionChange,
      fileTable,
      defaultTime1,
      defaultTime2,
    };
  },
});
</script>

<template>
  <div class="imgContainer">
    <div class="title">按文件下载</div>
    <div class="tableArea">
      <div class="left">
        <div class="leftTitle"><span>查询条件</span></div>
        <div class="leftMain">
          <div class="type">
            <p>文件类型</p>
            <el-select
              v-model="fileType"
              placeholder="请选择"
              style="width: 95%"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="time">
            <div class="start">
              <div class="name">开始时间</div>
              <el-date-picker
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 95%"
                :default-time="defaultTime1"
                v-model="startTime"
                type="datetime"
                placeholder="请选择时间"
              />
            </div>
            <div class="end">
              <div class="name">结束时间</div>
              <el-date-picker
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 95%"
                v-model="endTime"
                type="datetime"
                :default-time="defaultTime2"
                placeholder="请选择时间"
              />
            </div>
          </div>
          <!-- <div @click="searchFile" class="search"> -->
          <!-- <div class="searchBox"> -->
          <!-- <div class="icon"></div>
              <div>查找</div> -->
          <!-- </div> -->
          <!-- </div> -->
          <el-button
            :icon="Search"
            type="primary"
            @click="searchFile"
            style="margin-top: 12px; width: 100%; background-color: #fe6266"
            >查找</el-button
          >
        </div>
      </div>
      <div class="right">
        <div class="rightTitle">
          <div class="title"><span>文件列表</span></div>
          <div class="menu">
            <!-- <div @click="fileDownload">
              <span class="icon1" />
              <span>下载</span>
            </div> -->
            <!-- <div @click="cancelDown">
              <span class="icon2" />
              <span>停止下载</span>
            </div> -->
            <!-- <div @click="deleteFile">删除</div> -->

            <el-button
              class="iconBtn"
              :icon="Download"
              size="small"
              @click="fileDownload"
              >下载</el-button
            >
            <el-button
              class="iconBtn"
              :icon="Delete"
              size="small"
              @click="deleteFile"
              >删除</el-button
            >
          </div>
        </div>
        <div class="rightMain">
          <el-table
            ref="fileTable"
            :header-row-style="{ color: 'black' }"
            :border="true"
            :data="tableData"
            style="width: 100%"
            max-height="760"
            @select="handleSelectionChange"
          >
            <el-table-column align="center" type="selection" width="55" />
            <el-table-column align="center" type="index" label="序号" />
            <el-table-column align="center" prop="fileName" label="文件名" />
            <el-table-column align="center" prop="endTime" label="时间" />
            <el-table-column align="center" prop="fileSize" label="文件大小" />
            <el-table-column align="center" prop="address" label="下载进度" />
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss">
.imgContainer {
  width: 100%;
  padding: 20px;
  .title {
    height: 20px;
    line-height: 10px;
    font-size: 20px;
  }
  .tableArea {
    height: 800px;
    border: 1px solid black;
    .left {
      float: left;
      width: 16%;
      height: 100%;
      border-right: 1px solid black;
      .leftTitle {
        background-color: #e6e6e6;
        height: 30px;
        span {
          line-height: 30px;
          margin-left: 10px;
        }
      }

      .leftMain {
        padding: 20px 15px;

        .time {
          margin-top: 120px;
          .name {
            margin-bottom: 10px;
          }

          .end {
            margin-top: 20px;
          }
        }

        .search {
          margin-top: 100px;
          width: 95%;
          padding-top: 12px;
          height: 50px;
          background-color: #fe6266;
          .icon {
            width: 20px;
            height: 20px;
            background-image: url("@/assets/components/search.png");
            background-size: cover;
          }

          .searchBox {
            width: 80px;
            height: 30px;
            div {
              float: left;
              color: white;
            }
            margin: auto;
          }
        }
      }
    }

    .right {
      width: 84%;
      height: 100%;
      float: left;
      .rightTitle {
        background-color: #e6e6e6;
        height: 30px;

        .title {
          float: left;
          margin-left: 10px;
          span {
            line-height: 30px;
            margin-left: 10px;
          }
        }

        .menu {
          margin-right: 30px;
          float: right;
          // div {
          //   line-height: 24px;
          //   margin-left: 10px;
          //   float: left;
          //   height: 24px;
          //   width: 100px;
          //   text-align: center;
          //   margin-top: 3px;
          //   border: 1px solid black;
          //   cursor: pointer;

          //   .icon1 {
          //     width: 18px;
          //     height: 15px;
          //     display: inline-block;
          //     background-image: url("../../assets/components/download.png");
          //     background-size: cover;
          //     margin-right: 4px;
          //   }

          //   .icon2 {
          //     width: 18px;
          //     height: 15px;
          //     display: inline-block;
          //     background-image: url("../../assets/components/stopdown.png");
          //     background-size: cover;
          //     margin-right: 4px;
          //   }
          // }
          .iconBtn {
            margin-top: 3px;
          }
        }
      }
    }
  }

  th {
    .cell {
      .el-checkbox {
        .el-checkbox__input {
          display: none;
        }
      }
    }
  }
}
</style>
